package com.dynamic.mybatis.demo;

import com.alibaba.fastjson.JSON;
import com.dynamic.mybatis.core.builder.DynamicMapperAdapterBuilder;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.session.DynamicSqlSessionTemplate;
import com.dynamic.mybatis.mapper.CommonMapper;
import com.dynamic.mybatis.vo.DynamicSqlVo;
import org.apache.ibatis.session.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description
 * @Author xs
 * @Date 2021/3/25 16:52
 */
@Component
public class DynamicMybatisDemoRunner implements ApplicationRunner {

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private DynamicSqlSessionTemplate sqlSessionTemplate;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Configuration configuration = sqlSessionTemplate.getDynamicSqlSession().getSqlSession().getConfiguration();
        List<DynamicSqlVo> dynamicSqls = commonMapper.queryDynamicSQLListToInit();

        DynamicSqlVo sqlVo =  dynamicSqls.stream().filter(vo -> "queryDataBaseSystemInfo".equals(vo.getCode())).findFirst().get();

       new DynamicMapperAdapterBuilder( configuration ).parser(
               new DynamicMappedStatement.Builder()
               .setId(sqlVo.getCode())
               .setSqlCommandType(sqlVo.getOperateType())
               .setMappedStatement(sqlVo.getDynamicSql())
               .setReturnType(sqlVo.getReturnType()).builder()
           );
        Object result =  sqlSessionTemplate.execute("queryCurrentDateTime",null,"mysql");
        System.out.print("=====================");
        System.out.print(JSON.toJSONString(result));
    }
}